<?php

namespace App\Admin\Forms;

use App\Enums\ApplyStatus;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Exception;

class ReviewForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input): JsonResponse
    {
        $model = $this->payload['model']::find($this->payload['id']);

        if ($model->apply_status != ApplyStatus::REVIEW) {
            return $this->response()->error('当前状态无法操作');
        }

        switch ($input['result']) {
            case ApplyStatus::PASS->value:
                $model->pass(Admin::user());
                break;
            case ApplyStatus::REJECT->value :
                $model->reject(Admin::user(), $input['reason']);
        }

        return $this->response()->success('操作成功')->refresh();
    }

    public function form(): void
    {
        $this->textarea('apply_text', '申请说明')
            ->readOnly();
        $this->radio('result', '审核结果')
            ->options([
                ApplyStatus::PASS->value => '审核通过',
                ApplyStatus::REJECT->value => '驳回申请',
            ])
            ->default(ApplyStatus::PASS->value)
            ->required()
            ->when(ApplyStatus::REJECT->value, function () {
                $this->textarea('reason', '驳回原因');
            });
        $this->password('password', '操作密码')
            ->rules('required|current_password:admin')
            ->help('请输入当前账户密码以验证您的身份')
            ->required();
    }

    public function default(): array
    {
        $model = $this->payload['model']::find($this->payload['id'] ?? '');

        try {
            if ($model->apply_status == ApplyStatus::INIT) {
                $model->apply_status = ApplyStatus::REVIEW;
                $model->save();
            }
        } catch (Exception) {
        }

        return [
            'apply_text' => $model?->apply_text,
        ];
    }
}
